// src/app/workspace/[workspaceId]/member/[memberId]/components/chat-input.tsx
'use client';
import React, {useEffect, useRef, useState} from 'react';
import dynamic from 'next/dynamic'
import Quill from "quill";
import {useCreateMessage} from "@/features/messages/api/use-create-message";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {toast} from "sonner";
import {useCurrentUser} from "@/hooks/use-current-user";

const Editor = dynamic(() =>
    import('@/components/social/editor'), {ssr: false}
);

interface Props {
    placeholder: string
    conversationId: string
}

type  CreateMessageValues = {
    conversationId: string
    userId: string
    workspaceId: string
    body: string
    image: string
}

const ChatInputConversation = ({placeholder, conversationId}: Props) => {
    const user = useCurrentUser()

    const editorRef = useRef<Quill | null>(null)
    const [editorKey, setEditorKey] = useState(1)
    const [isPending, setIsPending] = useState(false)

    const workspaceId = useWorkspaceId()

    const {mutate: createMessage} = useCreateMessage();

    const handleSubmit = async ({
                                    body, image
                                }: {
        body: string,
        // image: File | null
        image: string | null
    }) => {
        try {
            setIsPending(true)
            editorRef?.current?.enable(false)

            const values: CreateMessageValues = {
                userId: user?.id!,
                conversationId, workspaceId, body,
                image: image as string
            }

            await createMessage(values, {throwError: true})

            setEditorKey((prevKey) => prevKey + 1)
            // editorRef?.current?.setContents([])}
        } catch (e) {
            toast.error('Failed to send message')
        } finally {
            setIsPending(false)
            editorRef?.current?.enable(true)
        }
    }

    return (
        <div className={`px-5 w-full`}>
            <Editor
                key={editorKey}
                // variant={'update'}
                placeholder={placeholder}
                // @ts-ignore
                onSubmit={handleSubmit}
                disabled={isPending}
                innerRef={editorRef}
            />
        </div>
    );
};

export default ChatInputConversation;